package com.phamlet.casualtopics;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Controller
@RequestMapping("/user")
public class UserController {

	private static Logger logger = Logger.getLogger( UserController.class );
    
    @ModelAttribute("users")
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<User> listUsers() throws IOException {    
            List<User> users = new ArrayList<User>();
            
            User user = new User();
//            user.setId(10001);
            user.setEmail("user.one@gmail.com");
            user.setName("User UNO");
            
            users.add(user);
            
            return users;
    }
    
    @ModelAttribute("user")
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public User saveUser( @RequestBody User user ) throws IOException {
            logger.debug(user);
            return user;
    }
    
    @ModelAttribute("user")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    
    public User userInfo() throws Exception {
            UserService userService = UserServiceFactory.getUserService();
            com.google.appengine.api.users.User gUser = userService.getCurrentUser();
            
            User user = new User();
            if(gUser != null) {
            	user.setEmail(gUser.getEmail());
            	user.setId(gUser.getUserId());
            	user.setName(gUser.getNickname());
            } else {
            	throw new Exception();
            }
            return user;
    }
    @ExceptionHandler(Exception.class)
    public void handleException(Throwable ex,HttpServletRequest req, HttpServletResponse res) throws IOException {
    	res.sendRedirect(UserServiceFactory.getUserService().createLoginURL(req.getRequestURI()));
    }

}
